// idea for future modifications:
// need something other than summation function.  Need objective function with goals for each segment.
// something like  Minimize: (SR1 - Goal1)**2 + (SR2 - Goal2)**2
// need to set SDLength = SR length !!
// maybe set sum only when min/max is satisfied ??

{
Indicator:          _SharpeRatio

Description:        Divides a time period into segments, and calculates price gain in percent for each segment.
                    If logarithmic growth is occuring, each segment will have a similar percentage gain.

                    Radarscreen: LOAD ADDITION DATA MUST BE SET TO AT LEAST = [Offset + SegLength*MaxList(Segments1,Segments2) + 3]

Calculation load:   With Offset=0, calculations include LastBarOnChart which is always changing with each tick.
                    Use this to ensure most recent data is included in analysis.

                    With Offset=1, calculations do NOT include LastBarOnChart.
                    This eliminates the constant calculations that are triggered while Close of current bar 
                    continuously updates with each tick throughout the day.
                    Use this setting to minimize calculation load while monitoring stocks during the day.

Note:               When RiskFreeReturn is > 0, the graph of sharpe ratio using this formula may appear to exhibit some instability,
                    abruptly changing values from plus to minus values.  This is because of the modification of the formula
                    where the sign of the RiskFreeReturn flips from positive to negative according to whether the 
                    AvgRR (Average rate of return) is a positive number or a negative.  This modification allows the forumla
                    to be used to screen for both potential longs and potential shorts, correctly adjusting the sign of the
                    RiskFreeReturn accordingly.

                    However, when using this calculation as a measure of performance, rather than for comparing potential 
                    long investments to potential short investments, it will be more useful to assume a RiskFreeReturn = 0.

                    This will remove any apparent "unstable" behavior in the sharpe ratio signal.

Author:             Mark J. Krisburg 

Last Modified:      06/04/07
                    01/09/08        Add RSSum = Mult1*SR1 + Mult2*SR2
                    01/21/08        Add 4th SR (SR4) and Summation output
                    08/18/08        improve consistency between chart and RS versions
                    04/27/10        ZScores are also multiplied by Mult coefficients to create SumZ
                    12/04/10        Add SmoothSR2 to avoid function errors when SmoothSR = 0
} 
 
Inputs:        
    Price(avgprice), 
    SegLength(1),                   // use = 1 for weekly or monthly monthly charts, = 5 for daily charts (1 week) or = 22 (1 month)
    SegsPerYear(251),               // = 52 if SegLength = 5 on Day Chart(1 week), = 12 if SegLength = 1 on Monthly Chart 
    Segments1(10),    
    Segments2(0),
    Segments3(0),
    Segments4(0),
    SmoothSR(1),                    // smoothing periods for SR plots
    SmoothSum(1),                   // smoothing periods for sum of SR
    SDLength(50),                   // length for standard deviation of SRSum
    SDMult(1),                      // multiplier for displaying SD bands

    Offset1(0),
    Offset2(0),
    Offset3(0),
    Offset4(0),

    Mult1(1),                        // multiplier for SR1     sum = Mult1*SR1 + Mult2*SR2 + Mult3*SR3 + Mult4*SR4
    Mult2(1),                        // multiplier for SR2     sum = Mult1*SR1 + Mult2*SR2 + Mult3*SR3 + Mult4*SR4
    Mult3(1),                        // multiplier for SR3     sum = Mult1*SR1 + Mult2*SR2 + Mult3*SR3 + Mult4*SR4
    Mult4(1),                        // multiplier for SR4     sum = Mult1*SR1 + Mult2*SR2 + Mult3*SR3 + Mult4*SR4

    RiskFreeReturn(0),               // annualized risk free return in percent.
    MaxAbsSRRatio12(3),              // maximum absolute SR ratio that will be displayed (to avoid distorting scale of other plots)
    CalcSeconds(60),                 // Recalculate SR every 'CalcTicks' tick.
    ShowSharpe(true),                // show Sharpe Ratios
    ShowRatio(False),                // Show ratio of SR1/SR2
    ShowSum(False),
    ShowSmoothSum(False),
    HiLoLength(3),                   // length used to calculate highest high and lowest low of xSRSum

    MinShortPrice(5),                // minimum price of stock that may be shorted
                                     // cause a recalculation (one day delay does not change result significantly).
    Ref1(0.00001),
    Ref2(8),
    Ref3(-8);
    
Vars:    
    SmoothSR2(MaxList(SmoothSR, 1)),                            
    x(0),                            // dummy variable
    StartBar1(0),                    // Bar number afterwhich calculations can begin for Segments1
    StartBar2(0),                    // Bar number afterwhich calculations can begin for Segments2
    StartBar3(0),                    // Bar number afterwhich calculations can begin for Segments3
    StopDate(CurrentDate),           // Last date to perform calculations.  (Default = Current Date)        

    avgRR1(0),                       // average return rate for 'Segments1' segments
    sdRR1(0),                        // standard deviation of return rates
    intrabarpersist annRR1(0),       // annualized rate of return = RR * 12 (1 segment = 1 month)
    annSD1(0),                       // annualized standard deviation of returns = sdRR * 12 (1 segment = 1 month)
    excessRR1(0),                    // excess return = annualized rate of return - risk free return
    intrabarpersist SR1(0),          // Sharpe Ratio = Excess return / annualized standard deviation of returns
    intrabarpersist AbsSR1(0),       // absolute value of Sharpe Ratio
    

    avgRR2(0),                       // average return rate for 'SegMents2' segments
    sdRR2(0),                        // standard deviation of return rates
    intrabarpersist annRR2(0),       // annualized rate of return = RR * 12 (1 segment = 1 month)
    annSD2(0),                       // annualized standard deviation of returns = sdRR * 12 (1 segment = 1 month)
    excessRR2(0),                    // excess return = annualized rate of return - risk free return
    intrabarpersist SR2(0),          // Sharpe Ratio = Excess return / annualized standard deviation of returns
    intrabarpersist AbsSR2(0),       // absolute value of Sharpe Ratio

    avgRR3(0),                       // average return rate for 'SegMents3' segments
    sdRR3(0),                        // standard deviation of return rates
    intrabarpersist annRR3(0),       // annualized rate of return = RR * 12 (1 segment = 1 month)
    annSD3(0),                       // annualized standard deviation of returns = sdRR * 12 (1 segment = 1 month)
    excessRR3(0),                    // excess return = annualized rate of return - risk free return
    intrabarpersist SR3(0),          // Sharpe Ratio = Excess return / annualized standard deviation of returns
    intrabarpersist AbsSR3(0),       // absolute value of Sharpe Ratio

    avgRR4(0),                       // average return rate for 'SegMents3' segments
    sdRR4(0),                        // standard deviation of return rates
    intrabarpersist annRR4(0),       // annualized rate of return = RR * 12 (1 segment = 1 month)
    annSD4(0),                       // annualized standard deviation of returns = sdRR * 12 (1 segment = 1 month)
    excessRR4(0),                    // excess return = annualized rate of return - risk free return
    intrabarpersist SR4(0),          // Sharpe Ratio = Excess return / annualized standard deviation of returns
    intrabarpersist AbsSR4(0),       // absolute value of Sharpe Ratio

    xSR1(0),                         // smoothed SR1
    xSR2(0),                         // smoothed SR2
    xSR3(0),                         // smoothed SR3
    xSR4(0),                         // smoothed SR4
    SRRatio12(0),                    // ratio of SR1/SR2
    SRSum(0),                        // sum of all Sharpe Ratios 
    SRSumZ(0),                       // sum of all Sharpe Ratio Z-Scores
    xSRSum(0),                       // smoothed SRSum
    DeltaSRSum(0),                   // change in value of SMOOTH SRSum
    DoCalc(True);                    // True when new SR calculation should be done            
    

DoCalc = _TickSeconds(CalcSeconds)> 0;    

if DoCalc then begin

    if Segments1 > 0 then x = _SharpeRatio(Price, SegLength, SegsPerYear, Segments1, RiskFreeReturn, 
        Offset1, avgRR1, sdRR1, annRR1, annSD1, excessRR1, SR1);
        
    if Segments2 > 0 then x = _SharpeRatio(Price, SegLength, SegsPerYear, Segments2, RiskFreeReturn, 
        Offset2, avgRR2, sdRR2, annRR2, annSD2, excessRR2, SR2);
        
    if Segments3 > 0 then x = _SharpeRatio(Price, SegLength, SegsPerYear, Segments3, RiskFreeReturn, 
        Offset3, avgRR3, sdRR3, annRR3, annSD3, excessRR3, SR3);
        
    if Segments4 > 0 then x = _SharpeRatio(Price, SegLength, SegsPerYear, Segments4, RiskFreeReturn, 
        Offset4, avgRR4, sdRR4, annRR4, annSD4, excessRR4, SR4);


    if SmoothSR > 1 then begin    
        xSR1 = _T3(SR1, SmoothSR2) * Mult1;
        xSR2 = _T3(SR2, SmoothSR2) * Mult2;
        xSR3 = _T3(SR3, SmoothSR2) * Mult3;
        xSR4 = _T3(SR4, SmoothSR2) * Mult4;    
    end else begin
        xSR1 = SR1 * Mult1;
        xSR2 = SR2 * Mult2;
        xSR3 = SR3 * Mult3;
        xSR4 = SR4 * Mult4;
    end;

    if ShowSharpe then begin
        if Segments1 <> 0 then Plot1(xSR1, "SR1");        
        if Segments2 <> 0 then Plot2(xSR2, "SR2");
        if Segments3 <> 0 then Plot3(xSR3, "SR3");
        if Segments4 <> 0 then Plot4(xSR4, "SR4");
    end;

end;


if ShowRatio then begin
    if xSR2 <> 0 then SRRatio12 = xSR1/xSR2 else SRRatio12 = 0;
    Plot21(Sign(SRRatio12)*MinList(AbsValue(SRRatio12), MaxAbsSRRatio12), "Ratio");
end;


    SRSum = xSR1 + xSR2 + xSR3 + xSR4;        

    if ShowSum then begin
        Plot22(SRSum, "SR Sum");
    end;

    if SmoothSum > 1 then begin
        xSRSum = _T3(SRSum, SmoothSum);
    end else begin
        xSRSum = SRSum;
    end; 
    
    if ShowSmoothSum then begin
        Plot23(xSRSum, "SRSum Smooth");
    end;

                                
if Ref1 <> 0 then Plot31(Ref1, "Ref1");
if Ref2 <> 0 then Plot32(Ref2, "Ref2");
if Ref3 <> 0 then Plot33(Ref3, "Ref3");